<?php

namespace app\service;

use app\model\Role;
use app\model\User;
use app\validate\RoleValidate;
use think\annotation\Inject;
use think\exception\ValidateException;

class RoleService
{
    /**
     * @Inject()
     * @var Role
     */
    protected $roleModel;

    /**
     * @Inject()
     * @var User
     */
    protected $userModel;

    /**
     * 获取角色列表
     * @param $param
     * @return array
     */
    public function getRoleList($param)
    {
        $limit = $param['pageSize'];

        $where = [];
        if (!empty($param['name'])) {
            $where[] = ['name', 'like', '%' . $param['name'] . '%'];
        }

        return $this->roleModel->getRoleList($limit, $where);
    }

    /**
     * 添加角色
     * @param $param
     * @return array
     */
    public function addRole($param)
    {
        try {

            validate(RoleValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-3, $e->getError());
        }

        $param['role_node'] = implode(',', $param['role_node']);

        return $this->roleModel->addRole($param);
    }

    /**
     * 编辑角色
     * @param $param
     * @return array
     */
    public function editRole($param)
    {
        try {

            validate(RoleValidate::class)->check($param);
        } catch (ValidateException $e) {
            return dataReturn(-3, $e->getError());
        }

        if ($param['status'] == 2) {
            $res = $this->userModel->getUserByRoleId($param['id']);
            if (!empty($res['data'])) {
                return dataReturn(-4, '该角色已经在使用，不可设置无效。');
            }
        }

        $param['role_node'] = implode(',', $param['role_node']);

        return $this->roleModel->editRole($param);
    }

    /**
     * 删除角色
     * @param $roleId
     * @return array
     */
    public function delRole($roleId)
    {
       $res = $this->userModel->getUserByRoleId($roleId);
       if (!empty($res['data']->toArray())) {
           return dataReturn(-1, '该角色已经在使用，不可删除。');
       }

       if ($res['code'] != 0) {
           return $res;
       }

       return $this->roleModel->delRole($roleId);
    }

    /**
     * 获取所有的角色
     * @return array
     */
    public function getAllRole()
    {
        return $this->roleModel->getAllList(['status' => 1], 'id value,name label');
    }
}